from flask import (
    Blueprint, flash, g, redirect, render_template, request, url_for
)
from werkzeug.exceptions import abort
from typing import List, Tuple
import sqlite3

from forumAPP.auth import login_required
from forumAPP.database import get_database_connection
from forumAPP.comment_tree import get_parent_comments, get_subtree_comments

bp = Blueprint('likes', __name__, url_prefix='/likes')


@bp.route('/')
@login_required
def launch():
    articleID: int = request.args.get('articleID')
    if articleID is None:
        return f"<h1>不可独立点赞,合法示例:{url_for('likes.launch',articleID=13)}</h1>"
    articleID = int(articleID)

    launcherID: int = g.user['numberID']

    # 判断是否已点赞; 选择点赞或者取消
    SQL_code: str = '''
    SELECT *
    FROM like_dislike
    WHERE articleID=? AND launcherID=?;
    '''
    conn = get_database_connection()
    whether_like = conn.execute(SQL_code, (articleID, launcherID,)).fetchone()
    # 未点赞
    if whether_like is None:
        SQL_code = '''
        INSERT INTO like_dislike
                (articleID, launcherID, direction)
        VALUES  (?,         ?,          true);
        '''
        conn.execute(SQL_code, (articleID, launcherID,))
        conn.commit()
    # 已点赞, 则取消
    else:
        SQL_code = '''
        DELETE FROM like_dislike
        WHERE numberID=?;
        '''
        conn.execute(SQL_code, (whether_like['numberID'],))
        conn.commit()
    return redirect(url_for('blog.detail', ID=articleID))
